package com.rtp2p.rtcoresdkdemo.add.lan

import android.app.Application
import android.content.Context
import android.widget.Toast
import com.rtp2p.rtcoresdkdemo.base.BaseViewModel
import com.rtp2p.rtp2pcore.common.RTCallback
import com.rtp2p.rtp2pcore.common.RTResp
import com.rtp2p.rtp2pcore.core.BindingDevice
import com.rtp2p.rtp2pcore.core.SearchDevice

class AddBindingLanViewModel(application: Application) : BaseViewModel(application) {
    var adapter: AddBindingLanAdapter? = null
        private set
    private var searchDevice: SearchDevice? = null
    fun init(context: Context) {
        adapter = AddBindingLanAdapter { deviceId ->
            binding(context, deviceId, "camra") {
                if (it.success) {
                    Toast.makeText(context, "$deviceId 绑定成功", Toast.LENGTH_SHORT).show()
                }
            }
        }
        searchDevice = SearchDevice(context) { callback ->
            if (callback.success) {
                val datas = adapter?.getDatas() ?: return@SearchDevice
                datas.forEach {
                    if (callback.data.equals(it)) return@SearchDevice
                }
                adapter?.add(callback.data)
            }
        }
    }

    fun startSearch() {
        searchDevice?.startSearch()
    }

    fun stopSearch() {
        searchDevice?.stopSearch()
    }

    //绑定设备
    private val bindingDevice = BindingDevice()
    private fun binding(
        context: Context,
        deviceId: String,
        deviceName: String,
        callback: RTCallback<RTResp<Unit>>
    ) {
        bindingDevice.binding(context, deviceId, deviceName, callback)
    }
}